package com.mtsmda.locales;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Locale;

public class LocaleEx {

	public static void main(String[] args) throws UnsupportedEncodingException {
		/*
		 * System.out.println(Locale.getDefault().getDisplayCountry() + " = " +
		 * Locale.getDefault().getDisplayLanguage() + " - " +
		 * Locale.getDefault().getDisplayName()); for(Locale locale :
		 * Locale.getAvailableLocales()){ System.out.println(locale.getCountry()
		 * + " = " + locale.getDisplayLanguage() + " - " +
		 * locale.getDisplayName() + " " + locale.getISO3Country()); }
		 */

		// String dima = new String("Д");
		// for (byte b : dima.getBytes(Charset.defaultCharset()))
		// System.out.println(b);

		// Charset defaultCharset = Charset.defaultCharset();
		// System.out.println(defaultCharset.displayName());

		/*
		 * String xmlstring = "Д"; String utf8string = convertToUTF8(xmlstring);
		 * int c = 0; for (int i = 0; i < utf8string.length(); ++i) { c += (int)
		 * utf8string.charAt(i); System.out.printf("%x ", (int)
		 * utf8string.charAt(i)); } System.out.println(c);
		 * 
		 * String string = "abc\u5639\u563b"; byte[] utf8 =
		 * string.getBytes("UTF-8"); for(byte b : utf8){ System.out.println(b);
		 * }
		 */

		String s = "Дима";
		/*
		 * byte ptext[] = s.getBytes("UTF8"); for (int i = 0; i < ptext.length;
		 * i++) { System.out.print(ptext[i] + ","); }
		 */
		System.out.println(native2Ascii(s));
		System.out.println(native2Ascii(s).equalsIgnoreCase(
				"\u0414\u0438\u043c\u0430"));
	}

	public static String native2Ascii(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char aChar = s.charAt(i);
			if ((aChar < 0x0020) || (aChar > 0x007e)) {
				sb.append('\\');
				sb.append('u');
				sb.append(toHex((aChar >> 12) & 0xF));
				sb.append(toHex((aChar >> 8) & 0xF));
				sb.append(toHex((aChar >> 4) & 0xF));
				sb.append(toHex(aChar & 0xF));
			} else {
				sb.append(aChar);
			}
		}
		return sb.toString();
	}

	private static char toHex(int nibble) {
		final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
				'9', 'A', 'B', 'C', 'D', 'E', 'F' };
		return hexDigit[nibble & 0xF];
	}

	// convert from UTF-8 -> internal Java String format
	public static String convertFromUTF8(String s) {
		String out = null;
		try {
			out = new String(s.getBytes("ISO-8859-1"), "UTF-8");
		} catch (java.io.UnsupportedEncodingException e) {
			return null;
		}
		return out;
	}

	// convert from internal Java String format -> UTF-8
	public static String convertToUTF8(String s) {
		String out = null;
		try {
			out = new String(s.getBytes("UTF-8"), "ISO-8859-1");
		} catch (java.io.UnsupportedEncodingException e) {
			return null;
		}
		return out;
	}

}